// index.js
// 获取应用实例
const app = getApp()
var mqtt = require('../../utils/mqtt.min.js')
var client = null
var pageData = {};
var humidity_echarts
var temperature_echarts
var illuminance_echarts
// echarts图表
import * as echarts from '../../components/ec-canvas/echarts.js'
Page({
  data: {
    lighticon: "/images/4.png",
    airConditionericon: "/images/8.png",
    humidifiericon: "/images/6.png",
    curtainicon: "/images/2.png",
    message: "",
    light_1_Status: 1,
    airConditioner_Status: 1,
    humidifier_Status: 1,
    curtain_Status: 1,
    humidity: 35,
    temperature: 24,
    illuminance: 117,
    dhttopic: '/classroom/105/humiture',
    ec: {
      onInit: initChart
    },
    ecBar: {
      onInit: initChart1
    },
    ecScatter: {
      onInit: initChart2
    }
  },
  onLoad() {
    this.connectMqtt();
    pageData = this;
    
    // setInterval(() => {
    //   temperature_echarts.setOption({
    //     series: [
    //       {
    //         data: [
    //           {
    //             value: this.temperature
    //           }
    //         ]
    //       }
    //     ]
    //   });
    //   humidity_echarts.setOption({
    //     series: [
    //       {
    //         data: [
    //           {
    //             value: this.humidity
    //           }
    //         ]
    //       }
    //     ]
    //   });
    //   illuminance_echarts.setOption({
    //     series: [
    //       {
    //         data: [
    //           {
    //             value: this.illuminance
    //           }
    //         ]
    //       }
    //     ]
    //   });
    // }, 5000);
  },
  onReady() {
    setTimeout(this.DraweCharts, 100)
  },
  connectMqtt: function () {
    var that = this
    const options = {
      connectTimeout: 4000,
      clinentId: 'WeChat_' + Math.random().toString(16).substr(2, 8),
      port: 8083,
    }
    client = mqtt.connect('wx://39.106.138.28/mqtt', options)
    client.on('connect', (e) => {
      console.log('服务器连接成功');
      client.subscribe('/classroom/105/humiture', {
        qos: 0
      }, function (err) {
        if (!err) {
          client.publish('/classroom/105/light_1', 'off');
          console.log('订阅成功');
        }
      })
    })
    // client.on('message',function(topic,message){
    //   console.log('收到' + message.toString());
    // })
    client.on("reconnect", (error) => {
      console.log("正在重连", error);
    });
    client.on("error", (error) => {
      console.log("连接失败", error);
    });
    //接收消息
    client.on('message', function (topic, message) {
      console.log(topic)
      var msg = message.toString()
      if (topic == that.data.dhttopic) { //如果是温湿度主题的消息
        //假设上传的数据为#23#45#off，其中温度是23，湿度45，led为关闭状态
        if (msg.indexOf("#") != -1) { //如果数据里包含#号，表示获取的是传感器值，因为单片机上传数据的时候用#号进行了包裹
          //如果有#号就进行字符串分割
          var all_data_arr = msg.split("#"); //分割数据，并把分割后的数据放到数组里。
          console.log(all_data_arr) //打印数组
          that.setData({ //数据赋值给变量
            temperature: all_data_arr[2], //赋值温度
            humidity: all_data_arr[1], //赋值湿度
          })
        }
      }
      //打印消息
      console.log('收到消息：' + msg)
    })
  },
  DraweCharts(){
    // console.log(temperature_echarts);
    // setInterval(() => {
    //   console.log(temperature_echarts);
    //   temperature_echarts.setOption({
    //     series: [
    //       {
    //         data: [
    //           {
    //             value: this.temperature
    //           }
    //         ]
    //       }
    //     ]
    //   });
    //   humidity_echarts.setOption({
    //     series: [
    //       {
    //         data: [
    //           {
    //             value: this.humidity
    //           }
    //         ]
    //       }
    //     ]
    //   });
    //   illuminance_echarts.setOption({
    //     series: [
    //       {
    //         data: [
    //           {
    //             value: this.illuminance
    //           }
    //         ]
    //       }
    //     ]
    //   });
    // }, 5000);
  },
  onChange0() {
    var that = this
    //如果点击前是打开状态，现在更换为关闭状态，并更换图标，完成状态切换
    if (that.data.light_1_Status == 1) {
      client.publish('/classroom/105/light_1', 'on')
      this.setData({
        lighticon: "/images/3.png", //设置led图片为off
        light_1_Status: 0
      });
    } else {
      //如果点击前是关闭状态，现在更换为打开状态，并更换图标，完成状态切换
      client.publish('/classroom/105/light_1', 'off')
      that.setData({
        lighticon: "/images/4.png", //设置led图片为on
        light_1_Status: 1
      });
    }
  },
  onChange1() {
    var that = this
    if (that.data.airConditioner_Status == 1) {
      client.publish('/classroom/105/airConditioner', 'on')
      this.setData({
        airConditionericon: "/images/7.png",
        airConditioner_Status: 0
      });
    } else {
      client.publish('/classroom/105/airConditioner', 'off')
      that.setData({
        airConditionericon: "/images/8.png",
        airConditioner_Status: 1
      });
    }
  },
  onChange2() {
    var that = this
    if (that.data.humidifier_Status == 1) {
      client.publish('/classroom/105/humidifier', 'on')
      this.setData({
        humidifiericon: "/images/5.png",
        humidifier_Status: 0
      });
    } else {
      client.publish('/classroom/105/humidifier', 'off')
      that.setData({
        humidifiericon: "/images/6.png",
        humidifier_Status: 1
      });
    }
  },
  onChange3() {
    var that = this;
    if (that.data.curtain_Status == 1) {
      client.publish('/classroom/105/curtain', 'on')
      this.setData({
        curtainicon: "/images/1.png",
        curtain_Status: 0
      });
    } else {
      client.publish('/classroom/105/curtain', 'off')
      that.setData({
        curtainicon: "/images/2.png",
        curtain_Status: 1
      });
    }
  },
})
//温度
function initChart(canvas, width, height, dpr) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  temperature_echarts = canvas;
  canvas.setChart(chart);

  var option = {
    series: [{
      type: 'gauge',
      center: ['50%', '70%'],
      startAngle: 200,
      endAngle: -20,
      min: -20,
      max: 40,
      splitNumber: 12,
      itemStyle: {
        color: '#FFAB91'
      },
      progress: {
        show: true,
        width: 30
      },
      pointer: {
        show: false
      },
      axisLine: {
        lineStyle: {
          width: 30
        }
      },
      axisTick: {
        distance: -38,
        splitNumber: 5,
        lineStyle: {
          width: 2,
          color: '#999'
        }
      },
      //短线
      splitLine: {
        distance: -40,
        length: 14,
        lineStyle: {
          width: 3,
          color: '#999'
        }
      },
      axisLabel: {
        distance: 1,
        color: '#999',
        fontSize: 10
      },
      anchor: {
        show: false
      },
      title: {
        show: false
      },
      detail: {
        valueAnimation: true,
        width: '40%',
        lineHeight: 40,
        borderRadius: 8,
        offsetCenter: [5, '-10%'],
        fontSize: 20,
        fontWeight: 'bolder',
        formatter: '{value} °C',
        color: 'auto'
      },
      data: [{
        value: pageData.data.temperature,
      }]

    }]
  };
  chart.setOption(option, true);
  return chart;
}
// 湿度
function initChart1(canvas, width, height, dpr) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  humidity_echarts = canvas
  canvas.setChart(chart);
  var option = {
    series: [{
      type: 'gauge',
      center: ['50%', '60%'],
      startAngle: 200,
      endAngle: -20,
      min: 0,
      max: 100,
      splitNumber: 10,
      itemStyle: {
        color: '#1E90FF'
      },
      progress: {
        show: true,
        width: 30
      },
      pointer: {
        show: false
      },
      axisLine: {
        lineStyle: {
          width: 30
        }
      },
      axisTick: {
        distance: -38,
        splitNumber: 5,
        lineStyle: {
          width: 2,
          color: '#999'
        }
      },
      //短线
      splitLine: {
        distance: -40,
        length: 14,
        lineStyle: {
          width: 3,
          color: '#999'
        }
      },
      axisLabel: {
        distance: 1,
        color: '#999',
        fontSize: 10
      },
      anchor: {
        show: false
      },
      title: {
        show: false
      },
      detail: {
        valueAnimation: true,
        width: '40%',
        lineHeight: 40,
        borderRadius: 8,
        offsetCenter: [5, '-10%'],
        fontSize: 20,
        fontWeight: 'bolder',
        formatter: '{value} RH',
        color: 'auto'
      },
      data: [{
        value: pageData.data.humidity,
      }]

    }]
  };
  chart.setOption(option, true);
  return chart;
}
// 光照度
function initChart2(canvas, width, height, dpr) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  illuminance_echarts = canvas;
  canvas.setChart(chart);
  var option = {
    series: [{
      type: 'gauge',
      center: ['50%', '60%'],
      startAngle: 200,
      endAngle: -20,
      min: 0,
      max: 1000,
      splitNumber: 10,
      itemStyle: {
        color: '#FFD700'
      },
      progress: {
        show: true,
        width: 30
      },
      pointer: {
        show: false
      },
      axisLine: {
        lineStyle: {
          width: 30
        }
      },
      axisTick: {
        distance: -38,
        splitNumber: 5,
        lineStyle: {
          width: 2,
          color: '#999'
        }
      },
      //短线
      splitLine: {
        distance: -38,
        length: 13,
        lineStyle: {
          width: 3,
          color: '#999'
        }
      },
      axisLabel: {
        distance: 1,
        color: '#999',
        fontSize: 10
      },
      anchor: {
        show: false
      },
      title: {
        show: false
      },
      detail: {
        valueAnimation: true,
        width: '40%',
        lineHeight: 40,
        borderRadius: 8,
        offsetCenter: [5, '-15%'],
        fontSize: 20,
        fontWeight: 'bolder',
        formatter: '{value} Lx',
        color: 'auto'
      },
      data: [{
        value: pageData.data.illuminance,
      }]
    }]
  };
  chart.setOption(option, true);
  return chart;
}